package com.ego.auth.controller;

import com.ego.auth.entity.UserInfo;
import com.ego.auth.properties.JwtProperties;
import com.ego.auth.service.AuthService;
import com.ego.auth.utils.JwtUtils;
import com.ego.common.utils.CookieUtils;
import com.ego.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletResponse httpServletResponse,
                                      HttpServletRequest httpServletRequest){

        //判断用户名密码是否正确
        User user = authService.checkUser(username,password);
        if (user == null) {
            //不正确->返回401
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        //正确->私钥创建token
        try {
            String token = JwtUtils.generateToken(new UserInfo(user.getId(), username), jwtProperties.getPrivateKey(), jwtProperties.getExpireMinutes());
            //向客户端写cookie
//            Cookie cookie = new Cookie(jwtProperties.getCookieName(),token);
//            cookie.setDomain("ego.com");
//            cookie.setPath("/");
//            cookie.setMaxAge(1000*60*jwtProperties.getExpireMinutes());
//            httpServletResponse.addCookie(cookie);
            CookieUtils.setCookie(httpServletRequest,httpServletResponse,jwtProperties.getCookieName(),token,jwtProperties.getMaxAge());
        } catch (Exception e) {
            log.error("授权失败",e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 验证用户信息
     * @param token token
     * @return 用户信息
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue("EGO_TOKEN") String token,
                                               HttpServletResponse httpServletResponse,
                                               HttpServletRequest httpServletRequest){

        UserInfo userInfo = null;
        try {
            // 从token中解析token信息
            userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            //刷新token
            token = JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpireMinutes());
            //重新写入cookie
            CookieUtils.setCookie(httpServletRequest,httpServletResponse,jwtProperties.getCookieName(),token,jwtProperties.getMaxAge());
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常则，响应500
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        // 解析成功返回用户信息
        return ResponseEntity.ok(userInfo);
    }
}
